import React, { useRef, useState } from 'react';
import { Divider, Button, Popconfirm } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { 
  getWorkerServiceListDetail,
  addService,
  updateService,
  dropService } from '@/services/order/api';
import { PlusOutlined } from '@ant-design/icons';
import ServiceForm from './ServiceForm';
import { showMsg, MsgType, isExits, isSupportSticky, isScroll } from '@/utils/utils';
import { OptType } from '@/utils/constants';

interface ServiceRecordProps {
  order_id?: string;
  detail?: ORDERAPI.ArchiveInfo;
  setShowPrint: (flag: boolean) => void
}

type ServiceItem = {
  worker_no?: string;
  service_id?: string;
  begin_time?: string;
  end_time?: string;
  day?: number;
  worker_id?: string;
  worker_name?: string;
  service_price?: string;
  create_date?: string;
  create_time?: string;
  status?: string;
  create_user_name?: string;
  real_total_recom_price?: string;
}

type ServiceItemList = {
  record_list?: ServiceItem[],
  sum_record_num?: number;
}

const ServiceRecord: React.FC<ServiceRecordProps> = (props) => {
  const { order_id = '', detail = {}, setShowPrint, onReload } = props;
  const actionRef = useRef<ActionType>();
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const columns: ProColumns<ServiceItem>[] = [
    {
      title: '护工编号',
      dataIndex: 'worker_no',
      width: 60
    },
    {
      title: '护工姓名',
      dataIndex: 'worker_name',
      width: 60
    },
    {
      title: '服务单号',
      dataIndex: 'service_id',
      width: isScroll ? 100 : 140,
    },
    {
      title: '服务开始时间',
      dataIndex: 'begin_time',
      width: isScroll ? 60 : 90,
    },
    {
      title: '服务结束时间',
      dataIndex: 'end_time',
      width: isScroll ? 60 : 90,
      render: (val, entity) => entity.is_check === 'Y' ? val : '-'
    },
    {
      title: '服务单价(天)',
      dataIndex: 'service_price',
      width: 65,
      valueType: 'money',
      align: 'right'
    },
    {
      title: '介绍费单价(天)',
      dataIndex: 'recom_price',
      width: 70,
      valueType: 'money',
      align: 'right'
    },
    {
      title: '服务天数',
      dataIndex: 'service_day',
      width: 45,
      align: 'right',
      render: (val, entity) => entity.is_check === 'Y' ? `${entity.check_day || entity.day}` : '-'
    },
    // {
    //   title: '核算状态',
    //   dataIndex: 'is_check',
    //   width: 60,
    //   align: 'right',
    //   renderText: (dom, entity) => dom === 'Y' ? '已核算' : '未核算'
    // },
    {
      title: '介绍费汇总',
      dataIndex: 'real_total_recom_price',
      width: 54,
      valueType: 'money',
      align: 'right'
    },
    {
      title: '缴费状态',
      dataIndex: 'recom_pay_flag',
      width: 45,
      align: 'right',
      renderText: (dom, entity) => dom === 'Y' ? '已缴费' : '未缴费'
    },
    {
      title: '记录创建时间',
      width: isScroll ? 60 : window.innerWidth < 1600 ? 62 : 105,
      renderText: (_, record) => {
        return record.create_date + ' ' + record.create_time;
      }
    },
    {
      title: '记录创建人',
      dataIndex: 'create_user_name',
      width: 55
    },
    {
      title: '记录状态',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      dataIndex: 'status',
      width: 45,
      valueType: 'select',
      valueEnum: {
        N: '正常',
        D: '已作废'
      },
      align: 'center'
    },
   
    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      align: 'center',
      width: 40,
      valueType: 'option',
      render: (_, record) => {
        return [
          // isExits('400403009') &&
          // <a key="edit" onClick={() => {
          //   setVisible(true);
          //   setCurrentRow(record);
          //   setOptType(OptType.VIEW);
          //   setServiceId(record.service_id as string);
          // }}>查看</a>,
          (record.status !== 'D' && record.recom_pay_flag !== 'Y' && isExits('400403010')) &&
          <Popconfirm 
            key="drop" 
            placement="topRight"
            okText="确认作废"
            cancelText="再想想"
            onConfirm={async () => {
              try {
                await dropService({
                  status: 'D',
                  service_id: record.service_id as string,
                  order_id: order_id
                });
                showMsg('已作废', MsgType.SUCCESS);
                actionRef.current?.reload();
              } catch (error) {
                showMsg(error?.data?.errmsg);
              }
            }}
            title="作废的记录将无法法恢复并不计入收款，是否继续？">
            <a>作废</a>
          </Popconfirm>
        ]
      }
    }
  ];
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<ServiceItem>({});
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const [serviceId, setServiceId] = useState<string>('');

  /**
   * 添加，编辑服务
   * @param fields 
   */
  const handleAdd = async (fields: ServiceItem) => {
    try {
      if (optType === OptType.ADD) {
        fields = Object.assign({}, fields, { order_id });
        await addService(fields);
      } else {
        fields = Object.assign({}, fields, { order_id, service_id: serviceId});
        await updateService(fields, '400403009');
      }
      showMsg('已保存', MsgType.SUCCESS);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  return <div className="service-record">
      <div className="header">
        <div className="title">2.服务记录</div>
      </div>
      <Divider style={{margin: '10px 0 0 !important'}}/>
      <ProTable<ServiceItem, COMMON.PageParams>
        rowKey="service_id"
        options={false}
        className="service-record-table"
        actionRef={actionRef}
        bordered
        request={async (params) => {
          if (!order_id) {
            return {
              data: [],
              total: 0,
              success: true
            }
          }
          try {
            params = Object.assign({}, params, { order_id });
            const data: ServiceItemList = await getWorkerServiceListDetail(params);
            setShowPrint(data.record_list?.length > 0);
            return {
              data: data.record_list,
              total: data.sum_record_num,
              success: true
            }
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              total: 0,
              success: true
            }
          }
        }}
        search={false}
        pagination={{
          showQuickJumper: true
        }}
        toolbar={{
          style: {
            display: ['C', 'P'].includes(detail.order_status as string) ? 'block' : 'none'
          },
          menu: {
            type: 'inline',
            
            items: [
              {
                key: 'add',
                label: (isExits('400403008') && ['C', 'P'].includes(detail.order_status as string)) ? <Button 
                  onClick={() => {
                    setVisible(true);
                    setCurrentRow({});
                    setOptType(OptType.ADD);
                    setServiceId('');
                  }} 
                  icon={<PlusOutlined />} 
                  type="primary">
                  添加
                </Button> : null
              }
            ]
          }
        }}
        columns={columns}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.service_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.service_id === clickRow ? 'tableRowClick' : ''
        }}
      />
      
      {
        visible && <ServiceForm 
          actionRef={actionRef}
          handleAdd={handleAdd}
          handleModalVisible={setVisible}
          record={currentRow}
          optType={optType}
          serviceType={detail.service_type}
          serviceId={serviceId}
          onReload={onReload}
        />
      }
  </div>
}

export default ServiceRecord;